package com.psmz.iwi.docanalyzer.core.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.psmz.iwi.docanalyzer.core.settings.ApplicationSettings;

public class DataSourceManager {

	/**
	 * Pobiera polaczenie do bazy.
	 * 
	 * @return Polaczenie do bazy.
	 * @throws SQLException
	 *             Wyrzucany w przypadku problemu z polaczeniem do bazy.
	 */
	public static Connection getConnection(ApplicationSettings settings)
			throws DaoException {
		try {
			Connection connection = DriverManager.getConnection(
					settings.getDatabaseConnectionString(),
					settings.getUserName(), settings.getPassword());
			connection.setAutoCommit(false);
			return connection;
		} catch (SQLException e) {
			throw new DaoException("Nie mozna pobrac polaczenia", e);
		}
	}

	public static void closeConnection(Connection connection)
			throws DaoException {
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				throw new DaoException("Nieudane zamkniecie polaczenia");
			}
		}
	}

	public static void rollbackTransaction(Connection connection)
			throws DaoException {
		if (connection != null) {
			try {
				connection.rollback();
			} catch (SQLException e) {
				throw new DaoException("Nieudane wycofanie transakcji");
			}
		}
	}

	public static void commitTransaction(Connection connection)
			throws DaoException {
		if (connection != null) {
			try {
				connection.commit();
			} catch (SQLException e) {
				throw new DaoException("Nieudane zatwierdzenie transakcji");
			}
		}
	}

	static {
		try {
			Class.forName("org.sqlite.JDBC");
		} catch (ClassNotFoundException e) {
			System.err.println("Nie zaladowano sterownika");
			System.err.println(e.toString());
		}

	}

}
